<?php
/**
 * Created by PhpStorm.
 * User: zws
 * Date: 2018/9/8
 * Time: 11:02
 * 检测人员管理
 */
namespace app\admin\service;

use app\common\model\ImageModel;
use app\common\model\MachineModel;
use app\common\model\OperateModel;
use app\common\model\ProtectModel;
use app\common\model\ReportModel;
use app\common\model\TemplateModel;
use app\common\model\UserModel;
use think\Db;

class ReportService
{
    protected static $reportModel;
    protected static $imageModel;
    protected static $operateModel;
    protected static $protectModel;
    protected static $machineModel;
    protected static $templateModel;
    protected static $userModel;
    protected $type;

    /**
     * ReportService constructor.
     * @param ReportModel $reportModel
     * @param ImageModel $imageModel
     * @param ProtectModel $protectModel
     * @param MachineModel $machineModel
     * @param TemplateModel $templateModel
     * @param UserModel $userModel
     * @param OperateModel $operateModel
     */
    public function __construct(ReportModel $reportModel,
                                ImageModel $imageModel,
                                ProtectModel $protectModel,
                                MachineModel $machineModel,
                                TemplateModel $templateModel,
                                UserModel $userModel,
                                OperateModel $operateModel)
    {
        self::$reportModel = $reportModel;
        self::$imageModel = $imageModel;
        self::$operateModel = $operateModel;
        self::$protectModel = $protectModel;
        self::$machineModel = $machineModel;
        self::$templateModel = $templateModel;
        self::$userModel = $userModel;
        $this->type = session('type');
        $this->type = 2;
    }

    /**
     * zws
     * 删除报告
     * @param $params
     * @return bool|void
     */
    public function del_report($params)
    {
        if (empty($params['id'])) {
            return app_fail(8592);
        }
        $report_data = self::$reportModel->where('id', '=', $params['id'])->find();
        if (empty($report_data)) {
            return app_fail(8591);
        }
        $user = self::$userModel->where(['id'=>$params['guid']])->find();
        // if (($user->type != 2 || $params['guid'] != $report_data['user_id']) && $user->type != 1) {
        //     return app_fail(9985);
        // }
        try {
            $result = self::$reportModel->where(['id' => $params['id']])->delete();
            return $result;
        } catch (\Exception $e) {
            return app_fail(9899);//编辑失败
        }
    }

    /**
     * zws
     * 获取报告
     * @param $params
     * @return array
     */
    public function get_report($params)
    {
        if($params['machine_type'] == 1)
        {
            //测试仪
            $where[] = ['machine_code', 'in' , $params['code']];
            $machine_data = self::$machineModel->where(['machine_code'=>$params['code']])
                ->find();
            if(!$machine_data)
            {
                //测试仪器不存在
                app_fail(8298);
            }
        }else{
            //保护
            $where[] = ['res_code', 'in' , $params['code']];
            $res_data = self::$protectModel->where(['res_code'=>$params['code']])->find();
            if(empty($res_data))
            {
                app_fail(8595);
            }
        }
        $count = self::$reportModel->where($where)
            ->count();
        if ($count < 1) {
            return ['links' => [], 'count' => (int) $count, 'type' => $params['page_type']];
        }
        if(!isset($params['page']) || empty($params['page'])){
            $params['page'] = 1;
        }
        if(!isset($params['limit']) || empty($params['limit'])){
            $params['limit'] = 20;
        }
        if($params['page'] > 0)
        {
            $result = self::$reportModel->where($where)
                ->page($params['page'], $params['limit'])
                ->order('create_time', 'desc')
                ->select();
        }else
        {
            $result = self::$reportModel->where($where)
                ->order('create_time', 'desc')
                ->select();
        }
        $datas = [];
        if($result)
        {
            $res_codes = [];
            $machine_codes = [];
            foreach ($result as $v)
            {
                $res_codes[] = $v['res_code'];
                $machine_codes[] = $v['machine_code'];
            }
            $res_datas = $this->get_protect($res_codes);
            $machine_datas = $this->get_machine($machine_codes);
            foreach ($result as $k=>$v)
            {
                $datas[$k] = array(
                    'id'=>$v['id'],
                    'name'=>$v['report_name'],
                    'res_code'=>$v['res_code'],
                    'machine_code'=>$v['machine_code'],
                    'template_id'=>$v['template_id'],
                    'proto'=>$v['report_proto'],
                    'res_name'=>isset($res_datas[$v['res_code']]) ? $res_datas[$v['res_code']] : '',
                    'machine_name'=>isset($machine_datas[$v['machine_code']]) ? $machine_datas[$v['machine_code']] : '',
                    'date' => $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '',
                    'url' => '',    // TODO 此处需要转 proto 的数据做成页面展示
                );

            }
        }
        return ['links' => $datas, 'count' => (int) $count, 'type' => $params['page_type']];
    }

    /**
     * zws
     * 获取模板
     * @param $params
     * @return array
     */
    public function get_template($params)
    {
        if($params['machine_type'] == 1)
        {
            //测试仪无模板
            app_fail(9997);
        }
        $res_data = self::$protectModel->where(['res_code'=>$params['code']])->find();
        if(empty($res_data))
        {
            app_fail(8595);
        }
        //保护
        $where[] = ['res_code', 'in' , $params['code']];
        $count = self::$templateModel->where($where)
            ->count();
        if ($count < 1) {
            return ['links' => [], 'count' => (int) $count, 'type' => $params['page_type']];
        }
        if(!isset($params['page']) || empty($params['page'])){
            $params['page'] = 1;
        }
        if(!isset($params['limit']) || empty($params['limit'])){
            $params['limit'] = 20;
        }
        if($params['page'] > 0)
        {
            $result = self::$templateModel->where($where)
                ->page($params['page'], $params['limit'])
                ->order('create_time', 'desc')
                ->select();
        }else
        {
            $result = self::$templateModel->where($where)
                ->order('create_time', 'desc')
                ->select();
        }
        $datas = [];
        if($result)
        {
            $res_codes = [];
            $template_ids = [];
            foreach ($result as $v)
            {
                $res_codes[] = $v['res_code'];
                $template_ids[] = $v['id'];
            }
            $res_datas = $this->get_protect($res_codes);
            $template_img_datas = $this->get_template_img($template_ids);
            foreach ($result as $k=>$v)
            {
                $datas[$k] = array(
                    'id'=>$v['id'],
                    'name'=>$v['template_name'],
                    'res_code'=>$v['res_code'],
                    'machine_code'=>'',
                    'template_id'=>'',
                    'proto'=>$v['template_proto'],
                    'res_name'=>isset($res_datas[$v['res_code']]) ? $res_datas[$v['res_code']] : '',
                    'machine_name'=>'',
                    'date' => $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '',
                    'url' => '',
                    'imgs' => isset($template_img_datas[$v['id']]) ?
                        $template_img_datas[$v['id']] : []
                );

            }
        }
        return ['links' => $datas, 'count' => (int) $count, 'type' => $params['page_type']];
    }

    /**
     * zws
     * 获取保护名称
     * @param $res_codes
     * @return array
     */
    public function get_protect($res_codes)
    {
        if(empty($res_codes) || !is_array($res_codes))
        {
            return [];
        }
        $where = [['res_code', 'in', $res_codes]];
        $datas = [];
        $result = self::$protectModel->where($where)->select();
        if($result)
        {
            foreach ($result as $v)
            {
                $datas[$v['res_code']] = $v['res_name'];
            }
        }
        return $datas;
    }

    /**
     * zws
     * 获取测试仪名称
     * @param $machine_codes
     * @return array
     */
    public function get_machine($machine_codes)
    {
        if(empty($machine_codes) || !is_array($machine_codes))
        {
            return [];
        }
        $where = [['machine_code', 'in', $machine_codes]];
        $datas = [];
        $result = self::$machineModel->where($where)->select();
        if($result)
        {
            foreach ($result as $v)
            {
                $datas[$v['machine_code']] = $v['machine_name'];
            }
        }
        return $datas;
    }

    /**
     * 获取模板图片
     * @param $template_ids
     * @return array
     */
    public function get_template_img($template_ids)
    {
        if(empty($template_ids) || !is_array($template_ids))
        {
            return [];
        }
        $where = [['template_id', 'in', $template_ids]];
        $datas = [];
        $result = self::$imageModel->where($where)->select();
        $path = config('param_config.imagePath');
        $filePath = config('app.app_host').substr($path, 1);
        if($result)
        {
            foreach ($result as $v)
            {
                $datas[$v['template_id']][] = [
                    'path'=>$v['path'],
                    'img_url'=>$v['img_url'] ? $filePath.$v['img_url'] : ''
                ];
            }
        }
        return $datas;
    }

    /**
     * zws
     * 根据res_code 或machine_code 获取报告信息
     * @param $params
     * @return array
     */
    public function report_info($params)
    {
        if(isset($params['machine_code']) && !empty($params['machine_code']))
        {
            //测试仪
            $where[] = ['machine_code', 'in' , $params['machine_code']];
            $machine_data = self::$machineModel->where(['machine_code'=>$params['machine_code']])
                ->find();
            if(!$machine_data)
            {
                //测试仪器不存在
                app_fail(8298);
            }
        }elseif(isset($params['res_code']) && !empty($params['res_code'])){
            //保护
            $where[] = ['res_code', 'in' , $params['res_code']];
            $res_data = self::$protectModel->where(['res_code'=>$params['res_code']])->find();
            if(empty($res_data))
            {
                app_fail(8595);
            }
        }else{
            return [];
        }
        $count = self::$reportModel->where($where)
            ->count();
        if ($count < 1) {
            return ['data' => [], 'count' => (int) $count];
        }
        if(!isset($params['page']) || empty($params['page'])){
            $params['page'] = 1;
        }
        if(!isset($params['limit']) || empty($params['limit'])){
            $params['limit'] = 10;
        }
        $result = self::$reportModel->where($where)
            ->page($params['page'], $params['limit'])
            ->order('create_time', 'desc')
            ->select();
        $datas = [];
        if($result)
        {
            $res_codes = [];
            $machine_codes = [];
            foreach ($result as $v)
            {
                $res_codes[] = $v['res_code'];
                $machine_codes[] = $v['machine_code'];
            }
            $res_datas = $this->get_protect($res_codes);
            $machine_datas = $this->get_machine($machine_codes);
            $userId = array_column($result->toArray(), 'user_id');
            $userDatas = self::$userModel->whereIn('id', $userId)->column('nickname', 'id');
            foreach ($result as $k=>$v)
            {
                $datas[$k] = array(
                    'id'=>$v['id'],
                    'name'=>$v['report_name'],
                    'res_code'=>$v['res_code'],
                    'machine_code'=>$v['machine_code'],
                    'template_id'=>$v['template_id'],
                    'proto'=>$v['report_proto'],
                    'nickname'=>isset($userDatas[$v['user_id']]) ? $userDatas[$v['user_id']] : '',
                    'res_name'=>isset($res_datas[$v['res_code']]) ? $res_datas[$v['res_code']] : '',
                    'machine_name'=>isset($machine_datas[$v['machine_code']]) ? $machine_datas[$v['machine_code']] : '',
                    'date' => $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '',
                    'url' => '',    // TODO 此处需要转 proto 的数据做成页面展示
                );

            }
        }
        return ['data' => $datas, 'count' => (int) $count];
    }


}